package org.darkforest.common.services.impl;

import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.lang.StringUtils;

import java.math.RoundingMode;
import java.util.Map.Entry;
import org.darkforest.common.services.*;
import org.darkforest.common.util.*;
import org.darkforest.common.wxpay.dto.WxPayResult;
import org.darkforest.dao.mapper.*;
import org.darkforest.enums.OrderLogEnum;
import org.darkforest.enums.OrderStatusEnum;
import org.darkforest.enums.PdLogTypeEnum;
import org.darkforest.enums.SettingNameEnum;
import org.darkforest.model.*;
import org.darkforest.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.nio.ShortBuffer;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Libing on 2015/3/20.
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private BundlingService bundlingService;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private CheckoutService checkoutService;
    @Autowired
    private DAddressMapper dAddressMapper;      //商家发货地址
    @Autowired
    private EnumParamMapper enumParamMapper;
    @Autowired
    private FestivalRemindMapper festivalRemindMapper;
    @Autowired
    private GiftCustomizationService giftCustomizationService;
    @Autowired
    private GoodsClassMapper goodsClassMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private InvoiceMapper invoiceMapper;
    @Autowired
    private MansongService mansongService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MessageAndNoticeService messageAndNoticeService;
    @Autowired
    private MemberMsgTplMapper memberMsgTplMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderBillMapper orderBillMapper;
    @Autowired
    private OrderCommonMapper orderCommonMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private OrderGiftCodeMapper orderGiftCodeMapper;
    @Autowired
    private OrderLogService orderLogService;
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private OrderPayMapper orderPayMapper;
    @Autowired
    private OrderStatisMapper orderStatisMapper;
    @Autowired
    private PdLogMapper pdLogMapper;
    @Autowired
    private PMiaoShaService miaoShaService;
    @Autowired
    private SimpleRedisService redisService;
    @Autowired
    private SimpleRedisService simpleRedisService;
    @Autowired
    private SettingService settingService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private TransportService transportService;
    @Autowired
    private VoucherService voucherService;
    @Autowired
    private VoucherTemplateService voucherTemplateService;


    public Order addOrder(OrderCreator orderCreator) throws Exception {
        logger.debug("create order params[userId:" + orderCreator.getUserId() + ",member:" + orderCreator.getMember().getUserId()
                + ",addressId:" + orderCreator.getAddressId() + ",payment:" + orderCreator.getPaymentCode() + ",totalPrice:" + orderCreator.getTotalPrice()
                + ",cartId:" + orderCreator.getCartId());
        //判断参数是否足够
        if (orderCreator.getUserId() == null || orderCreator.getMember().getUserId() == null
                || orderCreator.getAddressId() == null || orderCreator.getPaymentCode() == null
                || orderCreator.getTotalPrice() == null || (StringUtils.isBlank(orderCreator.getCartId()) && orderCreator.getCartIds() == null)) {
            throw new Exception("订单参数异常");
        }
        Order order = new Order();
        OrderPay orderPay = new OrderPay();
        String payNo = SerialNumGenerator.getOrderSn(SerialNumGenerator.ORDERCH_WEBCHART).toString();
        String[] cartIds = orderCreator.getCartIds() == null ? orderCreator.getCartId().trim().split(",") : orderCreator.getCartIds();
        int cart_db = 0;                                                        //根据cartId参数从数据库中获取cart数据的总数目
        Map<Integer, List<Cart>> cartMap = new HashMap<Integer, List<Cart>>();   //考虑到不同店铺的拆单问题,将购物车信息分类存储,key为店铺编号
//        BigDecimal totalPrice_db = new BigDecimal("0");
        for (String id : cartIds) {
            Integer cartId = Integer.parseInt(id);
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            if (cart != null) {
//                BigDecimal amount = cart.getAmount();
//                totalPrice_db = totalPrice_db.add(amount);
                List<Cart> carts = cartMap.get(cart.getStoreId());
                if (carts == null) {
                    carts = new ArrayList<Cart>();
                }
                carts.add(cart);
                cartMap.put(cart.getStoreId(), carts);
                cart_db++;
            }
        }

//        totalPrice_db = totalPrice_db.add(orderCreator.getFreight());
//        logger.debug("cart_db:"+cart_db+",cartIds.length:"+cartIds.length+",totalPrice:"+orderCreator.getTotalPrice()+",totalPrice_db"+totalPrice_db);
        //如有购物车id查询不到数据,或数据库总价与参数总价不等的情况，抛出异常
//        if(cart_db!=cartIds.length || !orderCreator.getTotalPrice().toString().equals(totalPrice_db.toString())){
//            throw new Exception("订单商品参数异常");
//        }
        //获取收货地址ID
        Address address = addressMapper.selectByPrimaryKey(orderCreator.getAddressId());
        //获取发票ID
        Invoice invoice = orderCreator.getInvoiceId() == null ? null : invoiceMapper.selectByPrimaryKey(orderCreator.getInvoiceId());

        //循环购物车Map，按店铺生成订单
        Iterator<Integer> cartMap_it = cartMap.keySet().iterator();
        while (cartMap_it.hasNext()) {
            Integer storeId = cartMap_it.next();                                    //获取店铺编号
            List<Cart> carts = cartMap.get(storeId);

            BigDecimal totalPrice_db = new BigDecimal(0);
            orderCreator.setTotalPrice(totalPrice_db);
            for (Cart cart : carts) {
                BigDecimal amount = cart.getAmount();
                totalPrice_db = totalPrice_db.add(amount);
                orderCreator.setTotalPrice(totalPrice_db);
                //检查库存 更新库存 更新销量
                Goods goods = goodsMapper.getGoodsById(cart.getGoodsId());
                if (goods.getGoodsStorage() < cart.getGoodsNum()) {
                    //库存不足时抛出异常阻止下单
                    throw new Exception("商品<" + cart.getGoodsName() + ">库存不足，请修改购物清单");
                }
                //库存充足情况 减少库存 增加销售量
                goods.setGoodsStorage(goods.getGoodsStorage() - cart.getGoodsNum());
                goods.setGoodsSalenum(goods.getGoodsSalenum() + cart.getGoodsNum());
                goodsMapper.updateGoodsStorage(goods);
                orderCreator.setFreight(this.orderShip(address, cart));
            }

            DAddress dAddress = dAddressMapper.selectByStoreId(storeId);           //获取店铺默认发货地址
            //组装order对象
            MemberBase member = orderCreator.getMember();
            order.setStoreId(storeId);
            order.setStoreName(carts.get(0).getStoreName());
            order.setBuyerId(member.getUserId());
            order.setBuyerName(member.getUserName());
            order.setBuyerEmail(member.getEmail());
            order.setGoodsAmount(orderCreator.getTotalPrice());         //暂时不考虑运费
            order.setOrderAmount(orderCreator.getTotalPrice().add(orderCreator.getFreight()));
            order.setPaymentCode(orderCreator.getPaymentCode());
            order.setAddTime(DateUtil.unixTimeStampInt().intValue());
            order.setOrderSn(SerialNumGenerator.getOrderSn(SerialNumGenerator.ORDERCH_WEBCHART));
            order.setOrderState("" + OrderStatusEnum.NON_PAYMENT.getValue());
            order.setOrderFrom("2");
            order.setLockState(0);
//            order_sn = order.getOrderSn().toString();
            order.setShippingFee(orderCreator.getFreight());                  //暂时全部免运费，运费模板出来以后修改 TODO
            order.setCoinAmount(0);
            Store store = storeService.selectStoreByPrimaryKey(storeId);
            if (store != null) {
                order.setSellerId(store.getMemberId());
            }
            orderMapper.insert(order);

            //组装orderCommon对象
            OrderCommon orderCommon = new OrderCommon();
            orderCommon.setOrderId(order.getOrderId());         //设置关联关系
            orderCommon.setStoreId(storeId);
            orderCommon.setDaddressId(dAddress == null ? 0 : dAddress.getAddressId());      //店铺发货地址
            orderCommon.setReciverName(address.getTrueName());
            orderCommon.setReciverInfo(JacksonsUtil.newInstance().readAsString(address));
            orderCommon.setReciverProvinceId(address.getAreaId());
            orderCommon.setReciverCityId(address.getCityId());
            orderCommon.setInvoiceInfo(invoice == null ? "" : JacksonsUtil.newInstance().readAsString(invoice));
            orderCommon.setPromotionInfo("");
            orderCommon.setDeliverExplain("");
            orderCommon.setOrderMessage(orderCreator.getRemark());
            orderCommonMapper.insert(orderCommon);

            //循环购物车列表，获取商品信息，组装order_goods对象
            for (Cart cart : carts) {
                Goods goods = goodsMapper.selectById(cart.getGoodsId());
                GoodsClass goodsClass = goodsClassMapper.selectByPrimaryKey(goods.getGcId());
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setStoreId(storeId);
                orderGoods.setBuyerId(member.getUserId());
                orderGoods.setOrderId(order.getOrderId());
                orderGoods.setGoodsId(goods.getGoodsId());
                orderGoods.setGoodsName(goods.getGoodsName());
                orderGoods.setGoodsImage(goods.getGoodsImage());
                orderGoods.setGoodsNum((int) cart.getGoodsNum());
                orderGoods.setGoodsPrice(goods.getGoodsPrice());
                orderGoods.setGoodsPayPrice(goods.getGoodsPrice());         //支付价格，后期有限时折扣或抢购的需要改变
                orderGoods.setGoodsType("1");                               //默认为实物商品，后续有虚拟商品再修改
                orderGoods.setGcId(goods.getGcId());
                orderGoods.setCommisRate(goodsClass.getCommisRate().shortValue());
                orderGoods.setCommisRateSecond(goodsClass.getCommisRateSecond().shortValue());
                orderGoodsMapper.insert(orderGoods);
                cartMapper.deleteByPrimaryKey(cart.getCartId());

                MidSEOrder midSEOrder = new MidSEOrder();
                midSEOrder.setFOrderNo(order.getOrderSn() + "");
                midSEOrder.setFOrderDate(new Date());
                midSEOrder.setFCustNo(order.getBuyerId() + "");
                midSEOrder.setFCustName(order.getBuyerName());
                midSEOrder.setFNeedInvoice((byte) (orderCommon.getInvoiceInfo().equals("") ? 0 : 1));
                midSEOrder.setFInvoiceTitle(orderCommon.getInvoiceInfo().equals("") ? "" : orderCommon.getInvoiceInfo());
                midSEOrder.setFItemNO(orderGoods.getGoodsId() + "");
                midSEOrder.setFItemName(orderGoods.getGoodsName());
                midSEOrder.setFQty(orderGoods.getGoodsNum());
                midSEOrder.setFPrice(orderGoods.getGoodsPrice().floatValue());
                midSEOrder.setFInputTime(new Date());
                midSEOrder.setFStatus(Integer.parseInt(order.getOrderState()));
                midSEOrder.setFKDTime(new Date());
//                midService.addMidSEOrder(midSEOrder);

            }

        }

        return order;
    }

    public OrderPay addOrderAndOrderPay(OrderCreator orderCreator) throws Exception {
        logger.debug("create order params[userId:" + orderCreator.getUserId() + ",member:" + orderCreator.getMember().getUserId()
                + ",addressId:" + orderCreator.getAddressId() + ",payment:" + orderCreator.getPaymentCode() + ",totalPrice:" + orderCreator.getTotalPrice()
                + ",cartId:" + orderCreator.getCartId());
        //判断参数是否足够
        if (orderCreator.getUserId() == null || orderCreator.getMember().getUserId() == null
                || orderCreator.getAddressId() == null || orderCreator.getPaymentCode() == null
                || orderCreator.getTotalPrice() == null || (StringUtils.isBlank(orderCreator.getCartId()) && orderCreator.getCartIds() == null)) {
            throw new Exception("订单参数异常");
        }
        Order order = new Order();
        OrderPay orderPay = new OrderPay();
        String payNo = SerialNumGenerator.getOrderSn(SerialNumGenerator.ORDERCH_WEBCHART).toString();
        String[] cartIds = orderCreator.getCartIds() == null ? orderCreator.getCartId().trim().split(",") : orderCreator.getCartIds();
        int cart_db = 0;                                                        //根据cartId参数从数据库中获取cart数据的总数目
        Map<Integer, List<Cart>> cartMap = new HashMap<Integer, List<Cart>>();   //考虑到不同店铺的拆单问题,将购物车信息分类存储,key为店铺编号
//        BigDecimal totalPrice_db = new BigDecimal("0");
        for (String id : cartIds) {
            Integer cartId = Integer.parseInt(id);
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            if (cart != null) {
//                BigDecimal amount = cart.getAmount();
//                totalPrice_db = totalPrice_db.add(amount);
                List<Cart> carts = cartMap.get(cart.getStoreId());
                if (carts == null) {
                    carts = new ArrayList<Cart>();
                }
                carts.add(cart);
                cartMap.put(cart.getStoreId(), carts);
                cart_db++;
            }
        }

//        totalPrice_db = totalPrice_db.add(orderCreator.getFreight());
//        logger.debug("cart_db:"+cart_db+",cartIds.length:"+cartIds.length+",totalPrice:"+orderCreator.getTotalPrice()+",totalPrice_db"+totalPrice_db);
        //如有购物车id查询不到数据,或数据库总价与参数总价不等的情况，抛出异常
//        if(cart_db!=cartIds.length || !orderCreator.getTotalPrice().toString().equals(totalPrice_db.toString())){
//            throw new Exception("订单商品参数异常");
//        }
        //获取收货地址ID
        Address address = addressMapper.selectByPrimaryKey(orderCreator.getAddressId());
        //获取发票ID
        Invoice invoice = orderCreator.getInvoiceId() == null ? null : invoiceMapper.selectByPrimaryKey(orderCreator.getInvoiceId());

        //循环购物车Map，按店铺生成订单
        Iterator<Integer> cartMap_it = cartMap.keySet().iterator();
        while (cartMap_it.hasNext()) {
            Integer storeId = cartMap_it.next();                                    //获取店铺编号
            List<Cart> carts = cartMap.get(storeId);

            CartInfoAjaxVo cartInfo = new CartInfoAjaxVo(carts);
            BigDecimal totalPromotion = new BigDecimal(0);

//             Todo #######################################满即送#######################################################################
            //满即送规则判断 如果存在多条满即送活动  默认取第一个活动对应的满减规则
            List<PMansong> pMansongList = mansongService.findListWithRuleByCondition(new PMansong(storeId, DateUtil.unixTimeStampInt().intValue(), (byte) 1));
            BigDecimal discountMoney = new BigDecimal(0);
            Integer promotionGoodsId = null;
            if (pMansongList.size() > 0) {
                for (int i = 0; i < pMansongList.get(0).getpMansongRuleList().size(); i++) {
                    PMansongRule rule = pMansongList.get(0).getpMansongRuleList().get(i);
                    //数据库中查询出                                                  来的是降序  将店铺的消费金额依次与店铺设定的减满消费比较 从大到小  如果大于或者等于就使用该减满 否则就下一轮循环
                    if (cartInfo.getSubtotal().compareTo(new BigDecimal(rule.getPrice())) == 1 || cartInfo.getSubtotal().compareTo(new BigDecimal(rule.getPrice())) == 0) {
                        //满减 不增送商品
                        if (rule.getDiscount() != 0 && rule.getGoodsId() == 0) {

                            discountMoney = new BigDecimal(rule.getDiscount());
                        }//不满减 只送礼品
                        else if (rule.getDiscount() == 0 && rule.getGoodsId() != 0) {
                            promotionGoodsId = rule.getGoodsId();
                        }//满减+赠送商品
                        else {
                            promotionGoodsId = rule.getGoodsId();
                            discountMoney = new BigDecimal(rule.getDiscount());
                        }
                        break;
                    } else {
                        continue;
                    }
                }
                //订单减免优惠
                totalPromotion = totalPromotion.add(discountMoney);
            }
//      Todo#######################################满即送#######################################################################

            BigDecimal totalPrice_db = new BigDecimal(0);
            orderCreator.setTotalPrice(totalPrice_db);
            for (Cart cart : carts) {
                BigDecimal amount = cart.getAmount();
                totalPrice_db = totalPrice_db.add(amount);
                orderCreator.setTotalPrice(totalPrice_db);

                if (cart.getBlId() == null || cart.getBlId() == 0) {
                    //检查库存 更新库存 更新销量
                    Goods goods = goodsMapper.getGoodsById(cart.getGoodsId());
                    if (goods.getGoodsStorage() < cart.getGoodsNum()) {
                        //库存不足时抛出异常阻止下单
                        throw new Exception("商品<" + cart.getGoodsName() + ">库存不足，请修改购物清单");
                    }
                    //库存充足情况 减少库存 增加销售量
                    goods.setGoodsStorage(goods.getGoodsStorage() - cart.getGoodsNum());
                    goods.setGoodsSalenum(goods.getGoodsSalenum() + cart.getGoodsNum());
                    goodsMapper.updateGoodsStorage(goods);
                }
//                orderCreator.setFreight(this.orderShip(address,cart));
            }
            //该满减之后的订单价格
            orderCreator.setTotalPrice(totalPrice_db.subtract(discountMoney));
            DAddress dAddress = dAddressMapper.selectByStoreId(storeId);           //获取店铺默认发货地址
            //组装order对象


            MemberBase member = orderCreator.getMember();
            order.setStoreId(storeId);
            order.setStoreName(carts.get(0).getStoreName());
            order.setBuyerId(member.getUserId());
            order.setBuyerName(member.getUserName());
            order.setBuyerEmail(member.getEmail());


//       Todo     ################################优惠券################################################
            //判断是否使用了优惠券 1 使用 0 不使用
            Voucher voucher = new Voucher();
            if ("1".equals(orderCreator.getUseVoucher())) {
                voucher = voucherService.selectByPrimaryKey(Integer.parseInt(orderCreator.getVoucherId()));
                order.setOrderAmount(orderCreator.getTotalPrice().add(orderCreator.getFreight()).subtract(new BigDecimal(voucher.getVoucherPrice())));
                order.setGoodsAmount(orderCreator.getTotalPrice().add(orderCreator.getFreight()));
                //使用优惠券优惠金额
                totalPromotion = totalPromotion.add(new BigDecimal(voucher.getVoucherPrice()));
            } else {
                order.setGoodsAmount(orderCreator.getTotalPrice().add(discountMoney));
                order.setOrderAmount(orderCreator.getTotalPrice().add(orderCreator.getFreight()));
            }
//       Todo     ################################优惠券################################################

            order.setPaymentCode(orderCreator.getPaymentCode());
            order.setAddTime(DateUtil.unixTimeStampInt().intValue());
            order.setOrderSn(SerialNumGenerator.getOrderSn(SerialNumGenerator.ORDERCH_WEBCHART));
            order.setOrderState("" + OrderStatusEnum.NON_PAYMENT.getValue());
            order.setOrderFrom("2");
            order.setLockState(0);
//            order_sn = order.getOrderSn().toString();
            order.setShippingFee(orderCreator.getFreight());                  //暂时全部免运费，运费模板出来以后修改 TODO
            order.setCoinAmount(0);
            Store store = storeService.selectStoreByPrimaryKey(storeId);
            if (store != null) {
                order.setSellerId(store.getMemberId());
            }
            orderMapper.insert(order);

            //添加支付信息
            orderPay.setBuyerId(order.getBuyerId() + "");
            orderPay.setApiPayState("0");
            orderPay.setOrderSn(order.getOrderSn() + "");
            orderPay.setOrderId(order.getOrderId());
            orderPayService.insert(orderPay);

            //组装orderCommon对象
            OrderCommon orderCommon = new OrderCommon();
            orderCommon.setOrderId(order.getOrderId());         //设置关联关系
            orderCommon.setStoreId(storeId);
            orderCommon.setDaddressId(dAddress == null ? 0 : dAddress.getAddressId());      //店铺发货地址
            orderCommon.setReciverName(address.getTrueName());
            orderCommon.setReciverInfo(JacksonsUtil.newInstance().readAsString(address));
            orderCommon.setReciverProvinceId(address.getAreaId());
            orderCommon.setReciverCityId(address.getCityId());
            orderCommon.setInvoiceInfo(invoice == null ? "" : JacksonsUtil.newInstance().readAsString(invoice));
            orderCommon.setPromotionInfo("");
            orderCommon.setDeliverExplain("");
            orderCommon.setOrderMessage(orderCreator.getRemark());
            orderCommon.setVoucherCode(orderCreator.getVoucherId() + "");
            orderCommon.setVoucherPrice(voucher.getVoucherPrice());
            orderCommon.setOrderMessage(orderCreator.getOrderMessage());
            orderCommonMapper.insert(orderCommon);

            if (promotionGoodsId != null) {
                Goods goods = goodsMapper.getGoodsById(promotionGoodsId);


                goods.setGoodsStorage(goods.getGoodsStorage() - 1);
                goods.setGoodsSalenum(goods.getGoodsSalenum() + 1);
                goodsMapper.updateGoodsStorage(goods);

                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setStoreId(storeId);
                orderGoods.setBuyerId(member.getUserId());
                orderGoods.setOrderId(order.getOrderId());
                orderGoods.setGoodsNum(1);
                orderGoods.setGoodsType("5");
                orderGoods.setGoodsId(goods.getGoodsCommonid());
                orderGoods.setGoodsName(goods.getGoodsName());
                orderGoods.setGoodsImage(goods.getGoodsImage());
                orderGoods.setGoodsPrice(new BigDecimal(0));
                orderGoods.setGoodsPayPrice(new BigDecimal(0));         //支付价格，后期有限时折扣或抢购的需要改变
                orderGoods.setGcId(goods.getGcId());
                orderGoods.setGoodsSpec(goods.getGoodsSpec());
                orderGoodsMapper.insert(orderGoods);


            }
            if ("1".equals(orderCreator.getUseVoucher())) {
                voucher.setVoucherState((byte) 2);
                voucher.setVoucherOrderId(orderCommon.getOrderId());
                //   修改已经使用优惠券的状态
                voucherService.updateByPrimaryKeySelective(voucher);
                //修改优惠券模板已经使用的优惠券数量
                voucherTemplateService.updateVoucherTplUserNumber(voucher.getVoucherTId());
                messageAndNoticeService.sendVoucherUseToUser(voucher);

            }

            //循环购物车列表，获取商品信息，组装order_goods对象


            for (int i = 0; i < carts.size(); i++) {
                Cart cart = carts.get(i);
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setStoreId(storeId);
                orderGoods.setBuyerId(member.getUserId());
                orderGoods.setOrderId(order.getOrderId());
                orderGoods.setGoodsNum((int) cart.getGoodsNum());
                orderGoods.setGoodsSpec(cart.getChooseGoodsSpec());
                orderGoods.setGoodsType("1");                               //默认为实物商品，后续有虚拟商品再修改
                //将所有优惠的总价按照商品的数量平摊到每个商品的支付价格
                //计算单个商品的优惠力度 如果没有优惠则为0
                BigDecimal divide = totalPromotion.divide(new BigDecimal(cartInfo.getCartQty()), 2, BigDecimal.ROUND_UP);

                if (cart.getBlId() == null || cart.getBlId() == 0) {
                    Goods goods = goodsMapper.selectById(cart.getGoodsId());

                    orderGoods.setGoodsId(goods.getGoodsId());
                    orderGoods.setGoodsName(goods.getGoodsName());
                    orderGoods.setGoodsImage(goods.getGoodsImage());
                    orderGoods.setGoodsPrice(goods.getGoodsPrice());


                    orderGoods.setGoodsPayPrice(goods.getGoodsPrice().subtract(divide));

                    orderGoods.setGcId(goods.getGcId());


                } else {
                    PBundling pBundling = bundlingService.getBundlingWithGoodsDetailByBlId(cart.getBlId(), 1);
                    orderGoods.setGoodsId(pBundling.getBlId());
                    orderGoods.setGoodsName(pBundling.getBlName());
                    orderGoods.setGoodsImage(pBundling.getpBundlingGoodsList().get(0).getGoodsImage());
                    orderGoods.setGoodsPrice(pBundling.getBlDiscountPrice());


                    orderGoods.setGoodsPayPrice(pBundling.getBlDiscountPrice().subtract(divide));


//                    orderGoods.setGoodsPayPrice(pBundling.getBlDiscountPrice());         //支付价格，后期有限时折扣或抢购的需要改变
//                    orderGoods.setGcId(goods.getGcId());
                    orderGoods.setGoodsType("4");
                    orderGoods.setPromotionsId(pBundling.getBlId());
                }
                orderGoodsMapper.insert(orderGoods);
                cartMapper.deleteByPrimaryKey(cart.getCartId());


            }

        }

        return orderPay;
    }

    public BigDecimal orderShip(Address dAddress, Cart cart) {
        //查询用户默认地址用来计算运费
        //运费
        BigDecimal orderShip = new BigDecimal(0);
        List<TransportFeeQuery> tsParam = new ArrayList<TransportFeeQuery>();
        Goods goods = goodsMapper.getGoodsById(cart.getGoodsId());
        tsParam.add(new TransportFeeQuery(cart.getStoreId(), goods.getGoodsId(), goods.getGoodsPrice(), cart.getGoodsNum().intValue(), goods.getTransportId(), goods.getGoodsFreight()));
        orderShip = transportService.getTransportFee(dAddress, tsParam, goods.getStoreId());              //计算运费
        return orderShip;
    }

    public Order updateOrderByPrimary(Order order) {
        orderMapper.updateByPrimaryKey(order);
        return order;
    }


    public OrderCommon updateOrderCommonByPrimaryP(OrderCommon orderCommon) {
        orderCommonMapper.updateByPrimaryKey(orderCommon);
        return orderCommon;
    }


    public OrderImformation getOrderImformationByPrimary(Integer orderId) {
        OrderImformation orderImformation = orderCommonMapper.getOrderImformationByPrimary(orderId);
        orderImformation.setOrder(orderMapper.selectByPrimaryKey(orderId));
        orderImformation.setOrderGoodsList(orderGoodsMapper.findOrderGoodsListByOrderId(orderId));
        return orderImformation;
    }

    @Override
    public List<Order> findOrderInfoByCondition(Order order) {
        return orderMapper.findOrderInfoByCondition(order);
    }

    @Override
    public PayInfoVo getPayInfoByPayno(String payNo) {
        PayInfoVo payInfo = new PayInfoVo();
        List<Order> orders = orderMapper.getOrderByPayno(payNo);
        Integer buyerId = 0;
        payInfo.setTotal_fee(new BigDecimal("0.00"));
        Integer orderId = 0;
        String oredrSn = "";
        for (Order order : orders) {
            if (order.getPdAmount() != null) {
                payInfo.setTotal_fee((order.getOrderAmount().subtract(order.getPdAmount())).add(payInfo.getTotal_fee()));
            } else {
                payInfo.setTotal_fee(order.getOrderAmount().add(payInfo.getTotal_fee()));
            }
            orderId = order.getOrderId();
            oredrSn = oredrSn + order.getOrderSn() + ",";
        }
        payInfo.setOrderId(orderId);
        payInfo.setPayNo(payNo);
        payInfo.setBuyerId(buyerId);
        payInfo.setOrderSn(oredrSn);
        return payInfo;
    }

    @Override
    public PayInfoVo getPayInfoBySn(String orderSn) {
        PayInfoVo payInfo = new PayInfoVo();
        Integer buyerId = 0;
        payInfo.setTotal_fee(new BigDecimal("0.00"));
        payInfo.setPdAmount(new BigDecimal("0.00"));
        Integer orderId = 0;
        String oredrSn = "";
        Order order = orderMapper.getOrderBySn(orderSn);
        if (order.getPdAmount() != null) {
            payInfo.setTotal_fee((order.getOrderAmount().subtract(order.getPdAmount())).add(payInfo.getTotal_fee()));
            payInfo.setPdAmount(order.getPdAmount().add(payInfo.getPdAmount()));
        } else {
            payInfo.setTotal_fee(order.getOrderAmount().add(payInfo.getTotal_fee()));
        }
        orderId = order.getOrderId();
        oredrSn = oredrSn + order.getOrderSn() + ",";

        payInfo.setOrderId(orderId);
        payInfo.setBuyerId(buyerId);
        payInfo.setOrderSn(oredrSn);
        return payInfo;
    }

    /**
     * 查询下单时间超过45分钟并且未支付的订单
     */
    public List<Order> CancleUnpayOrderList() {
        return this.orderMapper.CancleUnpayOrderList();
    }

    /**
     * 根据订单主键查询订单信息
     *
     * @param orderId
     * @return
     */
    @Override
    public Order selectOrderByPrimaryKey(Integer orderId) {
        return this.orderMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public List<OrderVo> selectListByCondition(OrderSearchBean page) {
        return orderMapper.selectListByCondition(page);
    }

    /**
     * 取消下单时间超过45分钟并且未支付的订单
     */
    public void updateOrderStatusByBatch(Map map) {
        orderMapper.updateOrderStatusByBatch(map);
    }

    /**
     * 创建秒杀订单
     *
     * @param orderCreator
     * @return
     * @throws Exception
     */
    @Override
    public Order addMsOrder(OrderCreator orderCreator) throws Exception {

        logger.debug("create order params[userId:" + orderCreator.getUserId() + ",member:" + orderCreator.getMember().getUserId()
                + ",addressId:" + orderCreator.getAddressId() + ",payment:" + orderCreator.getPaymentCode() + ",totalPrice:" + orderCreator.getTotalPrice());
        //判断参数是否足够
        if (orderCreator.getUserId() == null || orderCreator.getMember().getUserId() == null
                || orderCreator.getAddressId() == null || orderCreator.getPaymentCode() == null
                || orderCreator.getTotalPrice() == null) {
            throw new Exception("订单参数异常");
        }
        //检查该用户是否已参与过秒杀
        //检查用户是否已经秒杀过
        Integer userId = orderCreator.getUserId();
        String ms_users = redisService.getByKey("ms_users_" + orderCreator.getMiaosha().getMsId());
        JSONArray jsonArray = JSONArray.fromObject(ms_users);
        for (int i = 0; i < jsonArray.size(); i++) {
            Integer ms_userId = (Integer) jsonArray.get(i);
            if (userId == ms_userId) {
                throw new Exception("您已经参加过本次秒杀,请勿重复下单!");
            }
        }

        Order order = new Order();

        //获取收货地址ID
        Address address = addressMapper.selectByPrimaryKey(orderCreator.getAddressId());
        //获取发票ID
        Invoice invoice = orderCreator.getInvoiceId() == null ? null : invoiceMapper.selectByPrimaryKey(orderCreator.getInvoiceId());


        PMiaosha miaosha = orderCreator.getMiaosha();
        DAddress dAddress = dAddressMapper.selectByStoreId(miaosha.getStoreId());           //获取店铺默认发货地址


        //组装order对象
        MemberBase member = orderCreator.getMember();

        order.setStoreId(miaosha.getStoreId());
        order.setStoreName(miaosha.getStoreName());
        order.setBuyerId(member.getUserId());
        order.setBuyerName(member.getUserName());
        order.setBuyerEmail(member.getEmail());
        order.setGoodsAmount(miaosha.getMsPrice());         //暂时不考虑运费
        order.setShippingFee(new BigDecimal(miaosha.getYunFee()));
        order.setOrderAmount(orderCreator.getTotalPrice());
        order.setPaymentCode(orderCreator.getPaymentCode());
        order.setAddTime(DateUtil.unixTimeStampInt().intValue());
        order.setOrderSn(SerialNumGenerator.getOrderSn(SerialNumGenerator.ORDERCH_WEBCHART));
        order.setOrderState("" + OrderStatusEnum.NON_PAYMENT.getValue());
        order.setOrderFrom("2");
//            order_sn = order.getOrderSn().toString();
//            order.setShippingFee(new BigDecimal("0"));                  //暂时全部免运费，运费模板出来以后修改 TODO
        order.setCoinAmount(0);
        orderMapper.insert(order);

        //组装orderCommon对象
        OrderCommon orderCommon = new OrderCommon();
        orderCommon.setOrderId(order.getOrderId());         //设置关联关系
        orderCommon.setStoreId(miaosha.getStoreId());
        orderCommon.setDaddressId(dAddress == null ? 0 : dAddress.getAddressId());      //店铺发货地址
        orderCommon.setReciverName(address.getTrueName());
        orderCommon.setReciverInfo(JacksonsUtil.newInstance().readAsString(address));
        orderCommon.setReciverProvinceId(address.getAreaId());
        orderCommon.setReciverCityId(address.getCityId());
        orderCommon.setInvoiceInfo(invoice == null ? "" : JacksonsUtil.newInstance().readAsString(invoice));
        orderCommon.setPromotionInfo("");
        orderCommon.setDeliverExplain("");
        orderCommon.setOrderMessage(orderCreator.getRemark());
        orderCommonMapper.insert(orderCommon);


        //循环购物车列表，获取商品信息，组装order_goods对象
//            for(Cart cart : carts){
//                Goods goods = goodsMapper.selectById(cart.getGoodsId());
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setStoreId(miaosha.getStoreId());
        orderGoods.setBuyerId(member.getUserId());
        orderGoods.setOrderId(order.getOrderId());
        orderGoods.setGoodsId(miaosha.getGoodsId());
        orderGoods.setGoodsName(miaosha.getGoodsName());
        orderGoods.setGoodsImage(miaosha.getGoodsImage());
        orderGoods.setGoodsNum(1);
        orderGoods.setGoodsPrice(miaosha.getGoodsOrgPrice());
        orderGoods.setGoodsPayPrice(miaosha.getMsPrice());         //支付价格，后期有限时折扣或抢购的需要改变
        orderGoods.setGoodsType("2");                               //1普通，2秒杀
        orderGoods.setPromotionsId(miaosha.getMsId());
        orderGoods.setGcId(miaosha.getGcId());
        orderGoodsMapper.insert(orderGoods);
//                cartMapper.deleteByPrimaryKey(cart.getCartId());

        MidSEOrder midSEOrder = new MidSEOrder();
        midSEOrder.setFOrderNo(order.getOrderSn() + "");
        midSEOrder.setFOrderDate(new Date());
        midSEOrder.setFCustNo(order.getBuyerId() + "");
        midSEOrder.setFCustName(order.getBuyerName());
        midSEOrder.setFNeedInvoice((byte) (orderCommon.getInvoiceInfo().equals("") ? 0 : 1));
        midSEOrder.setFInvoiceTitle(orderCommon.getInvoiceInfo().equals("") ? "" : orderCommon.getInvoiceInfo());
        midSEOrder.setFItemNO(orderGoods.getGoodsId() + "");
        midSEOrder.setFItemName(orderGoods.getGoodsName());
        midSEOrder.setFQty(orderGoods.getGoodsNum());
        midSEOrder.setFPrice(orderGoods.getGoodsPrice().floatValue());
        midSEOrder.setFInputTime(new Date());
        midSEOrder.setFStatus(Integer.parseInt(order.getOrderState()));
        midSEOrder.setFKDTime(new Date());
//                midService.addMidSEOrder(midSEOrder);

//            }

//        }
        //数据库操作完毕后，更新redis数据
        jsonArray.add(orderCreator.getUserId());
        redisService.setValue("ms_users_" + orderCreator.getMiaosha().getMsId(), jsonArray.toString());
        String validAmt = redisService.getByKey("ms_validAmt_" + orderCreator.getMiaosha().getMsId());
        redisService.setValue("ms_validAmt_" + orderCreator.getMiaosha().getMsId(), "" + (Integer.parseInt(validAmt) - 1));
        miaoShaService.updatePurchasedNum(orderCreator.getMiaosha().getMsId());
//        for(int i=0;i<jsonArray.size();i++){
//            Integer ms_userId = (Integer)jsonArray.get(i);
//            if(userId==ms_userId){
//                throw new Exception("hasOrder");
//            }
//        }

        //清空购物车
        cartMapper.deleteByBuyerId(userId.toString());
        return order;
    }

    @Override
    public OrderVo selectById(int id) {
        return orderMapper.selectVoById(id);
    }

    @Override
    public void updateByPrimaryKeySelective(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Transactional
    public void orderPay(int memberId, String payNo, String pdAmount, String payType) {
        BigDecimal bd = new BigDecimal("0.00");
        BigDecimal pt = new BigDecimal(pdAmount);
        Member mb = memberMapper.getMemberById(memberId);
        //主账户
        Member owner = memberMapper.getMemberById(1);
        List<Order> orders = orderMapper.getOrderByPayno(payNo);
        PdLog pdLog = new PdLog();
        if (bd.compareTo(pt) != 0) {
            for (Order order : orders) {
                if (pt.compareTo(order.getOrderAmount()) >= 0) {
                    mb.setAvailablePredeposit(mb.getAvailablePredeposit().subtract(order.getOrderAmount()));
                    memberMapper.updateMemberBaseInfo(mb);
                    pdLog.setLgMemberId(mb.getMemberId());
                    pdLog.setLgMemberName(mb.getMemberName());
                    pdLog.setLgFreezeAmount(pt);
                    pdLog.setLgAddTime(Integer.parseInt(DateUtil.unixTimeStamp()));
                    pdLog.setLgDesc(OrderLogEnum.CREATE_ORDER.getInfo() + order.getOrderSn());
                    pdLog.setLgType("deposit");
                    pdLogMapper.insertSelective(pdLog);

                    //发送余额变动消息
                    messageAndNoticeService.sendPredepositChangeToUser(pdLog);


                    owner.setAvailablePredeposit(owner.getAvailablePredeposit().add(order.getOrderAmount()));
                    memberMapper.updateMemberBaseInfo(owner);
                    pdLog.setLgMemberId(owner.getMemberId());
                    pdLog.setLgMemberName(owner.getMemberName());
                    pdLog.setLgFreezeAmount(pt);
                    pdLog.setLgAddTime(Integer.parseInt(DateUtil.unixTimeStamp()));
                    pdLog.setLgDesc(OrderLogEnum.PAYMENT_DEPOSIT.getInfo() + order.getOrderSn());
                    pdLog.setLgType("order_pay");
                    pdLogMapper.insertSelective(pdLog);
                    //发送余额变动消息
                    messageAndNoticeService.sendPredepositChangeToUser(pdLog);

                    order.setPaymentCode("3");
                    order.setOrderState("20");
                    order.setPdAmount(order.getOrderAmount());
                    orderMapper.updateByPrimaryKeySelective(order);
                    pt = pt.subtract(order.getOrderAmount());

                    OrderLog orderLog = new OrderLog();
                    orderLog.setOrderId(order.getOrderId());
                    orderLog.setLogUser("" + order.getBuyerId());
                    orderLog.setLogRole("1");
                    orderLog.setLogOrderstate("" + OrderStatusEnum.WAIT_SHIPMENTS.getValue());
                    orderLog.setLogMsg("余额支付成功");
                    orderLog.setLogTime(DateUtil.unixTimeStampInt().intValue());
                    orderLogService.insert(orderLog);


                } else {

                    if (mb.getFreezePredeposit() != null) {
                        mb.setFreezePredeposit(mb.getFreezePredeposit().add(pt));
                    } else {
                        mb.setFreezePredeposit(pt);
                    }
                    mb.setAvailablePredeposit(mb.getAvailablePredeposit().subtract(pt));
                    memberMapper.updateMemberBaseInfo(mb);
                    pdLog.setLgMemberId(mb.getMemberId());
                    pdLog.setLgMemberName(mb.getMemberName());
                    pdLog.setLgFreezeAmount(pt);
                    pdLog.setLgAddTime(Integer.parseInt(DateUtil.unixTimeStamp()));
                    pdLog.setLgDesc(PdLogTypeEnum.ORDER_FREEZE.getText() + order.getOrderSn());
                    pdLog.setLgType("order_freeze");
                    pdLogMapper.insertSelective(pdLog);
                    //发送余额变动消息
                    messageAndNoticeService.sendPredepositChangeToUser(pdLog);

                    if (payType.equals("WX")) {
                        order.setPaymentCode("4");
                    } else {
                        order.setPaymentCode("5");
                    }
                    order.setPdAmount(pt.add(order.getPdAmount() != null ? order.getPdAmount() : new BigDecimal("0.00")));
                    orderMapper.updateByPrimaryKeySelective(order);
                    pt = new BigDecimal("0.00");
                }
                if (bd.compareTo(pt) == 0) {
//                    order.setPaymentCode("2");
//                    orderMapper.updateByPrimaryKeySelective(order);
                    break;
                }
            }
        } else {
            for (Order order : orders) {
                if (order.getPdAmount() != null && order.getPdAmount().compareTo(bd) != 0) {
                    if (payType.equals("WX")) {
                        order.setPaymentCode("4");
                    } else {
                        order.setPaymentCode("5");
                    }
                } else {
                    if (payType.equals("WX")) {
                        order.setPaymentCode("1");
                    } else {
                        order.setPaymentCode("2");
                    }
                }
                orderMapper.updateByPrimaryKeySelective(order);
            }
        }
    }

    /**
     * 查询订单交易情况
     *
     * @param storeId
     * @return
     */
    @Override
    public Map<String, Object> findTransactionInfo(Integer storeId) {
        List<Map<String, Object>> list = null;
        list = orderMapper.findTransactionInfo(storeId);
        Map<String, Object> map = getRegionHashMap(list);
        return map;
    }

    /**
     * 取消超时45分钟未支付订单
     */
    @Override
    @Transactional
    public void cancleUnpayOrder() {
        logger.info("取消下单超过30分钟未支付的订单 每10分钟执行一次:" + new Date());
        List<Order> orders = orderMapper.CancleUnpayOrderList();
        List<Integer> list = new ArrayList<Integer>();
        int date = DateUtil.unixTimeStampInt().intValue();
        for (Order order : orders) {
            OrderLog ol = new OrderLog();

            ol.setLogTime(date);
            ol.setLogRole("0"); //系统 0
            ol.setLogUser("0"); //默认 0
            ol.setLogOrderstate("10");
            ol.setOrderId(order.getOrderId());
            logger.info("日志表记录已经取消的订单" + new Date());
            List<OrderGoods> orderGoodsList = orderGoodsMapper.findOrderGoodsListByOrderId(order.getOrderId());
            for (OrderGoods orderGoods : orderGoodsList) {
                Goods goods = new Goods(orderGoods.getGoodsId(), orderGoods.getGoodsNum());
                //恢复库存
                goodsMapper.restoreGoodsStorege(goods);
            }
            ol.setLogMsg(order.getOrderId() + "订单超时自动取消");
            //将已经取消的未支付超时订单记录订单日志表
            orderLogService.insertSelective(ol);
            list.add(order.getOrderId());
        }
        if (orders.size() > 0) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("list", list);
            map.put("orderState", "0");
            map.put("finishTime", DateUtil.unixTimeStampInt().intValue());
            logger.info("执行批量取消订单操作" + new Date());
            //修改超时未支付订单为取消状态
            orderMapper.updateOrderStatusByBatch(map);
        }
    }

    @Override
    @Transactional
    public int doCancelOrder(Order orderOne, MemberBase admin) {
        try {
            // 根据  order.getOrderBatchNumber()，order.getOrderBatchNumber()  取得下单时生成的所有订单
            Order orderTemp = new Order();
            orderTemp.setOrderBatchNumber(orderOne.getOrderBatchNumber());
            orderTemp.setBuyerId(orderOne.getBuyerId());
            orderTemp.setAddTime(orderOne.getAddTime());
            List<Order> orderList = orderMapper.findOrderInfoByCondition(orderTemp);

            int date = DateUtil.unixTimeStampInt().intValue();

            for (Order order : orderList) {
                order.setFinnshedTime(date);
                order.setOrderState("0");
                updateByPrimaryKeySelective(order);

                OrderLog ol = new OrderLog();
                ol.setLogMsg(order.getOrderId() + "管理员取消订");
                ol.setLogTime(date);
                ol.setLogRole("0"); //系统 0
                ol.setLogUser(admin.getUserId().toString()); //默认 0
                ol.setLogOrderstate("10");
                ol.setOrderId(order.getOrderId());
                orderLogService.insertSelective(ol);

                logger.info("日志表记录已经取消的订单" + new Date());
                List<OrderGoods> orderGoodsList = orderGoodsMapper.findOrderGoodsListByOrderId(order.getOrderId());
                for (OrderGoods orderGoods : orderGoodsList) {
                    Goods goods = new Goods(orderGoods.getGoodsId(), orderGoods.getGoodsNum());
                    goodsMapper.restoreGoodsStorege(goods);
                }
            }
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
        }

        return 0;
    }

    /**
     * 微信扫码支付成功之后
     *
     * @param wpr
     */
    @Override
    @Transactional
    public void wxPayCallBack(WxPayResult wpr) {
        //修改订单状态
        OrderPay orderPay = new OrderPay();

        if ("SUCCESS".equals(wpr.getReturnCode()) && "SUCCESS".equals(wpr.getResultCode())) { //支付成功

//            order = orderMapper.getOrderBySn(wpr.getOutTradeNo());
            List<Order> orders = orderMapper.getOrderByPayno(wpr.getOutTradeNo());
            for (Order order : orders) {
                if (order.getOrderState().equals("10")) {
                    //订单表修改状态
                    order.setOrderState("20");
                    order.setPaySn(wpr.getTransactionId());
                    orderMapper.updateOrderStatusByOrderSN(order);


                    //支付成功记录订单历史表
                    OrderLog orderLog = new OrderLog();
                    orderLog.setLogMsg("微信支付成功");
                    orderLog.setOrderId(order.getOrderId());
                    orderLog.setLogOrderstate("10"); //支付完成后记录订单前一状态
                    orderLog.setLogRole("1");
                    orderLog.setLogUser(order.getBuyerId() + "");
                    orderLog.setLogTime(DateUtil.unixTimeStampInt().intValue());
                    orderLogService.AddOrderLog(orderLog);
                    if (order.getPdAmount() != null && order.getPdAmount().compareTo(BigDecimal.ZERO) != 0) {
                        payForPdAmount(order);
                    }

                }

            }


        }
    }


    @Override
    @Transactional
    public int payForPdAmount(Order order) {
        Member leader = memberMapper.getMemberById(1);
        Member buyer = memberMapper.getMemberById(order.getBuyerId());
        int i = 0;
//      更新余额
        buyer.setFreezePredeposit(buyer.getFreezePredeposit().subtract(order.getPdAmount()));
        i = memberMapper.updateMemberBaseInfo(buyer);
//      记录日志
        PdLog buyerPdLog = new PdLog();
        buyerPdLog.setLgMemberId(buyer.getMemberId());
        buyerPdLog.setLgMemberName(buyer.getMemberName());
        buyerPdLog.setLgAddTime(DateUtil.unixTimeStampInt().intValue());
        buyerPdLog.setLgType("order_comb_pay");
        buyerPdLog.setLgFreezeAmount(order.getPdAmount());
        buyerPdLog.setLgAvAmount(BigDecimal.ZERO);
        buyerPdLog.setLgDesc(order.getOrderSn() + "支付被冻结的预存款" + order.getPdAmount() + "元");
        pdLogMapper.insert(buyerPdLog);

        //发送余额变动消息
        messageAndNoticeService.sendPredepositChangeToUser(buyerPdLog);

        // 更新余额
        leader.setAvailablePredeposit(leader.getAvailablePredeposit().add(order.getPdAmount()));
        i = memberMapper.updateMemberBaseInfo(leader);
//      记录日志
        PdLog leaderPdLog = new PdLog();
        leaderPdLog.setLgMemberId(leader.getMemberId());
        leaderPdLog.setLgMemberName(leader.getMemberName());
        leaderPdLog.setLgAddTime(DateUtil.unixTimeStampInt().intValue());
        leaderPdLog.setLgType("order_pay");
        leaderPdLog.setLgFreezeAmount(BigDecimal.ZERO);
        leaderPdLog.setLgAvAmount(order.getPdAmount());
        leaderPdLog.setLgDesc(order.getOrderSn() + "支付余额" + order.getPdAmount() + "元");
        pdLogMapper.insert(leaderPdLog);
        //发送余额变动消息
        messageAndNoticeService.sendPredepositChangeToUser(leaderPdLog);

        return i;
    }

    /**
     * 定时任务 超过10天的订单设置自动收货 并且自动评价  暂不开发2016-01-17
     */
    @Override
    @Transactional
    public void AutoReceiveAndEvaluate() {
        logger.info("超过10天 订单状态为未收货的订单");
        //查询未收货并且离已经发货的时间已经超过10天的订单
        List<Order> orderList = orderMapper.selectNotReceiveAndTimeoutOrder();
        List<Integer> list = new ArrayList<Integer>();
        for (Order order : orderList) {
            OrderLog ol = new OrderLog();
            ol.setLogMsg(order.getOrderId() + "订单超时自动确认收获");
            ol.setLogTime(DateUtil.unixTimeStampInt().intValue());
            ol.setLogRole("0"); //系统 0
            ol.setLogUser("0"); //默认 0
            ol.setLogOrderstate("30");
            ol.setOrderId(order.getOrderId());
            orderLogService.insertSelective(ol);
            list.add(order.getOrderId());
        }
        if (orderList.size() > 0) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("list", list);
            map.put("orderState", "40");
            map.put("finishTime", DateUtil.unixTimeStampInt().intValue());
            logger.info("执行批量订单自动收货操作" + new Date());
            //修改超时未支付订单为取消状态
            orderMapper.updateOrderStatusByBatch(map);
        } else {
            logger.info("超时自动收货评价--没有符合条件的订单");
        }
    }

    @Override
    public List<Map<String, Object>> findGoodsTop30ByCondition(Order order) {
        return orderMapper.findGoodsTop30ByCondition(order);
    }

    @Override
    public List<Map<String, Object>> findAmountByCondition(Order order) {
        return orderMapper.findAmountByCondition(order);
    }

    @Override
    public List<Map<String, Object>> findIndexByCondition(Order order) {
        return orderMapper.findIndexByCondition(order);
    }

    /**
     * 根据时间内容查询订单
     *
     * @param order
     * @return
     */
    @Override
    public List<Order> selectOrderListByDateCondition(OrderSearchBean order) {
        return orderMapper.selectOrderListByDateCondition(order);
    }

    @Override
    public Map<String, Object> staticsOrderAmountByDateCondition(OrderSearchBean order) {
        List<Map<String, Object>> list = orderMapper.staticsOrderAmountByDateCondition(order);
        return getRegionHashMap(list);
    }

    /**
     * 根据时间统计订单销售量
     *
     * @param order
     * @return
     */
    @Override
    public Map<String, Object> staticsOrderCountByDateCondition(OrderSearchBean order) {
        List<Map<String, Object>> list = orderMapper.staticsOrderCountByDateCondition(order);
        return getRegionHashMap(list);
    }

    /**
     * 根据时间统计订单销售额以及销售量
     *
     * @param order
     * @return
     */
    @Override
    public Map<String, Object> staticsOrderCountAndAmountByDateCondition(OrderSearchBean order) {
        List<Map<String, Object>> list = orderMapper.staticsOrderCountAndAmountByDateCondition(order);
        return getRegionHashMap(list);
    }

    /**
     * 下单
     *
     * @param postType
     * @param payType
     * @param codeNum
     * @param addressId
     * @param invoiceId   发票ID
     * @param member      @return
     * @param cartChannel
     */
    @Transactional
    public AjaxReturnEntity saveOrder(Integer postType, Integer payType, Integer codeNum, Integer addressId, Integer invoiceId, Member member, Integer cartChannel) {
        //订单批次号 用于拆单
        Long ORDER_BATCH_NUMBER = SerialNumGenerator.getOrderBatchNum();
        String ORDER_SN = "";
        Long firstOrderSn= new Long(0);
        AjaxReturnEntity ajaxReturnEntity = new AjaxReturnEntity();

        BigDecimal totalFee = new BigDecimal(0);
        List<Cart> cartList = new ArrayList<Cart>();
        if (cartChannel == 1) {
            cartList = cartMapper.selectCheckedCartsByMemberId(member.getMemberId());

        } else {
            String cartStr = simpleRedisService.getByKey(member.getMemberId() + "_buy_goods");
            if (StringUtils.isNotBlank(cartStr)) {
                Cart cart = JSONUtils.toBean(cartStr, Cart.class);
                cartList.add(cart);
            } else {
                ajaxReturnEntity.setDatas(null);
                ajaxReturnEntity.setResult(false);
                ajaxReturnEntity.setMessage("购物车内无商品，请勿下单");
                return ajaxReturnEntity;
            }
        }

        if (cartList.size() < 1) {
            ajaxReturnEntity.setDatas(null);
            ajaxReturnEntity.setResult(false);
            ajaxReturnEntity.setMessage("购物车内无商品，请勿下单");
            return ajaxReturnEntity;
        }

        //减商品库存
        for (Cart cart : cartList) {
            Goods goods = goodsMapper.selectById(cart.getGoodsId());
            if (goods == null) {
                ajaxReturnEntity.setDatas(null);
                ajaxReturnEntity.setResult(false);
                ajaxReturnEntity.setMessage("商品【" + cart.getGoodsName() + "】参数错误");
                return ajaxReturnEntity;
            } else if (goods.getGoodsState() != 1) {
                ajaxReturnEntity.setDatas(null);
                ajaxReturnEntity.setResult(false);
                ajaxReturnEntity.setMessage("商品【" + goods.getGoodsName() + "】已下架");
                return ajaxReturnEntity;
            } else if (cart.getGoodsNum() > goods.getGoodsStorage()) {
                ajaxReturnEntity.setDatas(null);
                ajaxReturnEntity.setResult(false);
                ajaxReturnEntity.setMessage("商品【" + goods.getGoodsName() + "】库存不足");
                return ajaxReturnEntity;
            } else {
                goods.setGoodsStorage(goods.getGoodsStorage() - cart.getGoodsNum());
                goods.setGoodsSalenum(goods.getGoodsSalenum() + cart.getGoodsNum());
                goodsMapper.updateGoodsStorage(goods);
            }
        }

        //获取发票信息
        String invoiceInfo = null;
        if (invoiceId != 0) {
            Invoice invoice = invoiceMapper.selectByPrimaryKey(invoiceId);
            invoiceInfo = invoice == null ? invoiceInfo : JSONObject.toJSONString(invoice);
        }

        //获取购物车内商品从那几个店铺购买
        Set<Integer> storeIdsSet = new HashSet<Integer>();
        for (Cart cart : cartList) {
            storeIdsSet.add(cart.getStoreId());
        }

        // 获取员工折扣
        BigDecimal empDiscount = new BigDecimal(100);
        // 员工级别的取得
        MemberWithBLOBs memberInfo = memberMapper.selectByPrimaryKey(member.getMemberId());
        Integer employeeLevel = memberInfo.getEmployeeLevel();
        if (employeeLevel != null && employeeLevel > 0) {
            // 员工折扣的取得
            EnumParam enumParam = new EnumParam();
            enumParam.setPageSwitch(false);
            enumParam.setParamType("employee_Level");
            String empLevel = "V" + employeeLevel;
            enumParam.setParamKey(empLevel);
            enumParam.setParamState(1);
            List<EnumParam> list = enumParamMapper.selectListByCondition(enumParam);
            if ((list != null) && (list.size() > 0)) {
                empDiscount = new BigDecimal(list.get(0).getParamValue());
            }
        }

        // 订单添加时的时间是相同的
        int orderAddTime = DateUtil.unixTimeStampInt().intValue();

        //遍历已买的店铺 并且获取在该店铺购买的商品
        for (Integer storeId : storeIdsSet) {
            Store store = storeService.selectStoreByPrimaryKey(storeId);
            List<Cart> simpleStoreCart = new ArrayList<Cart>();
            if (cartChannel != 1) {
                simpleStoreCart = cartList;
            } else {
                simpleStoreCart = cartService.findCartList(member.getMemberId().toString(), "1", storeId);
            }

//            cartList.addAll(simpleStoreCart);
//            CartInfoAjaxVo cartInfo = new CartInfoAjaxVo(simpleStoreCart);

            BigDecimal totalPrice = new BigDecimal(0);
            BigDecimal goodsTotalPrice = new BigDecimal(0);
            BigDecimal shipfee = new BigDecimal(0);

            Map map = checkoutService.orderCheckoutBySimpleStore(member, addressId, codeNum, postType, cartChannel, storeId);
            if ("true".equals(map.get("result"))) {
                goodsTotalPrice = new BigDecimal(map.get("cartTotalAmount").toString());
                shipfee = new BigDecimal(map.get("shipAmount").toString());
                //totalPrice = goodsTotalPrice.add(shipfee);
                totalPrice = new BigDecimal(map.get("totalAmount").toString());
            } else {
                ajaxReturnEntity.setDatas(null);
                ajaxReturnEntity.setResult(false);
                ajaxReturnEntity.setMessage(map.get("msg").toString());
                return ajaxReturnEntity;
            }

            Order order = new Order();

            //组装order对象
            order.setBuyerId(member.getMemberId());
            order.setBuyerName(member.getMemberName());
            order.setBuyerEmail(member.getMemberEmail());
            order.setStoreId(storeId);
            order.setStoreName(store.getStoreName());
            order.setPaymentCode("1");
            order.setAddTime(orderAddTime);
            order.setOrderSn(SerialNumGenerator.getOrderSn(SerialNumGenerator.ORDERCH_WEBCHART));
            order.setOrderBatchNumber(ORDER_BATCH_NUMBER);
            order.setOrderFrom("2");
            order.setLockState(0);
            order.setShippingFee(shipfee);                  //暂时全部免运费
            order.setOrderAmount(totalPrice);           // 订单支付的实际价格
            totalFee = totalFee.add(totalPrice);
            totalFee = totalFee.setScale(2, RoundingMode.HALF_UP);
            order.setGoodsAmount(goodsTotalPrice);     // 商品的实际价格
            order.setEvaluationState("0");
            order.setOrderState("" + OrderStatusEnum.NON_PAYMENT.getValue());
            orderMapper.insertSelective(order);

            firstOrderSn = order.getOrderId().longValue();
            ORDER_SN = order.getOrderSn() + ",";

            //组装orderCommon对象
            OrderCommon orderCommon = new OrderCommon();
            orderCommon.setOrderId(order.getOrderId());         //设置关联关系
            orderCommon.setStoreId(storeId);
            //如果是直接配送
            if (postType == 1) {
                Address address = addressMapper.selectByPrimaryKey(addressId);
                orderCommon.setReciverName(address.getTrueName());
                orderCommon.setReciverInfo(JacksonsUtil.newInstance().readAsString(address));
                orderCommon.setReciverProvinceId(address.getAreaId());
                orderCommon.setReciverCityId(address.getCityId());
            }

            orderCommon.setCodeNum(codeNum);
            orderCommon.setPostType(postType);
            orderCommon.setPayType(payType);
            orderCommon.setInvoiceInfo(invoiceInfo);
            orderCommonMapper.insert(orderCommon);

            for (Cart cart : simpleStoreCart) {
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setStoreId(storeId);
                orderGoods.setBuyerId(member.getMemberId());
                orderGoods.setOrderId(order.getOrderId());
                orderGoods.setGoodsId(cart.getGoods().getGoodsId());
                orderGoods.setGoodsName(cart.getGoods().getGoodsName());
                orderGoods.setGoodsImage(cart.getGoods().getGoodsImage());
                orderGoods.setGoodsNum(codeNum != 0 ? codeNum * (int) cart.getGoodsNum() : (int) cart.getGoodsNum());
                orderGoods.setGoodsPrice(cart.getGoods().getGoodsPrice());
                //支付价格，后期有限时折扣或抢购的需要改变
                BigDecimal goodsPayPrice = cart.getGoods().getGoodsPrice();
                // 员工价
                if (empDiscount.compareTo(new BigDecimal(100)) < 0) {
                    goodsPayPrice = goodsPayPrice.multiply(empDiscount).divide(new BigDecimal(100));
                    goodsPayPrice = goodsPayPrice.setScale(2, RoundingMode.HALF_UP);
                }
                orderGoods.setGoodsPayPrice(goodsPayPrice);
                orderGoods.setGoodsType("1");
                orderGoods.setGoodsSpec(cart.getGoods().getGoodsSpec());
                orderGoods.setGcId(cart.getGoods().getGcId());
                orderGoods.setAddTime(DateUtil.unixTimeStampInt().intValue());
                orderGoods.setCostPrice(cart.getGoods().getCostPrice());
                orderGoods.setCommisType(cart.getGoods().getCommissionType());  // 分拥类型
                orderGoods.setCommisRate(cart.getGoods().getCommissionRate().shortValue());  // 分拥比例
                orderGoodsMapper.insert(orderGoods);
                cartMapper.deleteByPrimaryKey(cart.getCartId());
            }
        }

        //添加支付信息
        OrderPay orderPay = new OrderPay();
        orderPay.setBuyerId(member.getMemberId().toString());
        orderPay.setApiPayState("0");
        orderPay.setOrderSn(ORDER_BATCH_NUMBER + "");
        orderPayService.insert(orderPay);

        Order returnObj = new Order();
        returnObj.setPaymentCode("1");
        returnObj.setOrderState("10");
        returnObj.setOrderAmount(totalFee);
        returnObj.setOrderId(ORDER_BATCH_NUMBER.intValue());
        returnObj.setOrderSns(ORDER_SN.substring(0, ORDER_SN.length() - 1));
        returnObj.setOrderSn(firstOrderSn);
        ajaxReturnEntity.setResult(true);
        ajaxReturnEntity.setDatas(returnObj);
        ajaxReturnEntity.setMessage("succ");
        simpleRedisService.deleteByKey(member.getMemberId() + "_buy_goods");
        return ajaxReturnEntity;
    }

    @Transactional
    public boolean wxJsApiPayCallBack(List<OrderVo> orderVos, OrderPay orderPay, String bank_type, String transaction_id, String pay_order_sn, String orderSn) {

        OrderVo orderVo = orderVos.get(0);
        Integer buyerId = orderVo.getBuyerId();
        String buyerName = orderVo.getBuyerName();
        OrderCommon orderCommon = orderCommonMapper.selectByPrimaryKey(orderVo.getOrderId());
        if (orderPay != null) {
            orderPay.setPayType(1);
            orderPay.setApiPayState("1");
            orderPay.setBuyerId(buyerId + "");

            orderPay.setBankType(bank_type);
            orderPay.setTransactionId(transaction_id);
            orderPay.setPayOrderSn(orderSn);
            orderPayMapper.updateByPrimaryKeySelective(orderPay);
        } else {
            orderPay.setPayType(1);
            orderPay.setApiPayState("1");
            orderPay.setBuyerId(buyerId + "");
            orderPay.setOrderSn(orderSn);
            orderPay.setBankType(bank_type);
            orderPay.setTransactionId(transaction_id);
            orderPay.setPayOrderSn(pay_order_sn);
            orderPayMapper.insertSelective(orderPay);
        }

        for (OrderVo o : orderVos) {
            //修改订单状态
            if (orderCommon.getPostType() == 2)
                // 礼品码方式30
                o.setOrderState("30");
            else {
                o.setOrderState("20");
            }
            o.setPaymentCode("1");
            o.setPaymentTime(DateUtil.unixTimeStampInt().intValue());
            o.setPaySn(transaction_id);
            orderMapper.updateByPrimaryKeySelective(o);

            // 短信发送
            // 自己购买时，付完款后就发短信
            // 送礼时，收礼者填完收货地址后再发短信
            if (orderCommon.getPostType() == 1) {
                System.out.println("订单【" + o.getOrderId() + "】的短信发送开始。。。。。");
                try {
                    String phoneNum = settingService.getSettingInfo(SettingNameEnum.OPERATION_MOBILE_PHONE);
                    MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("order_payment_success");

                    Map<String, Object> smsMap = new HashMap<String, Object>();
                    smsMap.put("moblieNumber", phoneNum);
                    // 【央联E家】你好，2018年x月x日xx时，您的xx店铺，xx商品被某某拍下N件（个），并已经付款，请及时发货！
                    // 【央联E家】你好，{1}，您的{2}店铺，{3}拍下了{4}，并已经付款，请及时发货！
                    String[] params = new String[4];
                    //  yyyy年MM月dd日 HH时mm分ss秒
                    String strDateTime =  DateUtil.toGbkStrDate(o.getPaymentTime());
                    strDateTime = strDateTime.substring(0, strDateTime.length() - 3);
                    params[0] = strDateTime;  // yyyy年MM月dd日 HH时mm分
                    params[1] = o.getStoreName();
                    params[2] = o.getBuyerName();
                    // xx商品N件（个）、xx商品N件（个）
                    String goodsInfo = "";
                    List<OrderGoods> goodsList = orderGoodsMapper.findOrderGoodsListByOrderId(o.getOrderId());
                    for (OrderGoods orderGoods: goodsList) {
                        if (!"".equals(goodsInfo)) {
                            goodsInfo = goodsInfo + "、";
                        }
                        goodsInfo = goodsInfo + orderGoods.getGoodsName() + "商品" + orderGoods.getGoodsNum() + "件（个）";
                    }
                    params[3] = goodsInfo;
                    smsMap.put("params", params);

                    messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
                } catch (Exception e){
                    e.printStackTrace();
                    logger.error("订单【" + o.getOrderId() + "】的短信发送失败：", e);
                }finally {
                    System.out.println("订单【" + o.getOrderId() + "】的短信发送结束。。。。。");
                }
            }
        }

        List<String> giftCodes = new ArrayList<String>();
        if (orderCommon.getPostType() == 2) {
//            String QRCodePath = System.getProperty("user.dir");
//            Map<String,String> imageMap = new HashMap<String,String>();
            for (int i = orderCommon.getCodeNum(); i >= 1; i--) {
                OrderGiftCode orderGiftCode = new OrderGiftCode();
                orderGiftCode.setGenerateOrderId(orderSn);
                orderGiftCode.setCreateName(buyerName);
                orderGiftCode.setCreateTime(DateUtil.getCurrentDateTime());
                orderGiftCode.setCreaterId(buyerId);
                orderGiftCode.setCodeState(1);
                List<String> gc = InvertCodeGenerator.genCodes(6, 1);
                int count = orderGiftCodeMapper.selectCountByCode(gc.get(0));
                while (count > 0) {
                    gc = InvertCodeGenerator.genCodes(6, 1);
                }
                giftCodes.addAll(gc);
                orderGiftCode.setGiftCode(gc.get(0));
                orderGiftCodeMapper.insertSelective(orderGiftCode);

                // 生成二维码
                //QRCodeUtil.encode(gc.get(0), 240, 240, Constants.QRCODE_GENERATE_PATH + gc.get(0) + "_" + buyerId + ".jpg");
//                String imgCid = gc.get(0) + "_" + buyerId;
//                String QRCodeFileName = QRCodePath + System.getProperty("file.separator") + imgCid + ".jpg";
//                QRCodeUtil.encode(gc.get(0), 240, 240, QRCodeFileName);
//
//                imageMap.put(imgCid, QRCodeFileName);
            }

            //发送二维码邮件
//            Member member = memberMapper.getMemberById(buyerId);
//            String[] receivers = {member.getMemberEmail()};
//            String title = "您的送礼二维码";
//            String content = "您的送礼二维码为：";  // content不起作用，但不设定时，163等将会把该邮件作为垃圾邮件，不予以发送
////            MailUtil.sendMail(title, content.toString(), reciver, fileNames, senderFiles, true);
//            String retVal = MailUtil.sendMailBySSL(title, content, SystemConstant.USERNAME.trim(), receivers , imageMap, null);
//
//            //删除二维码的临时文件
//            if("success".equals(retVal) || "fail".equals(retVal) ) {
//                Set<Map.Entry<String, String>> set = imageMap.entrySet();
//                for (Iterator iterator = set.iterator(); iterator.hasNext();) {
//                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
//                    File file = new File(entry.getValue());
//                    if (file.exists()) {
//                        file.delete();
//                        logger.debug("删除二维码文件：" + file.getName());
//                    }
//                }
//            }
        }
        return true;
    }

    /**
     * 将一些特殊的List<Map<String,Object>> 转化成Map<String,Object>
     *
     * @param regionMap
     * @return
     */
    public static Map<String, Object> getRegionHashMap(List<Map<String, Object>> regionMap) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        for (Map<String, Object> map : regionMap) {
            String code = null;
            Object value = null;
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if ("code_field".equals(entry.getKey())) {
                    code = entry.getValue() + "";
                } else if ("value_field".equals(entry.getKey())) {
                    value = entry.getValue();
                }
            }
            resultMap.put(code, value);
        }
        return resultMap;
    }

    /**
     * *
     * 会员消费额统计，会员等级
     */
    @Override
    @Transactional
    public void orderBalance() {
        Order order = new Order();
        order.setPageSwitch(false);
        List<Order> list = orderMapper.orderBalance(order);
        for (Order or : list) {
            MemberWithBLOBs member = memberMapper.selectByPrimaryKey(or.getBuyerId());
            member.setConsumeAmt(member.getConsumeAmt().add(or.getOrderAmount()));
            member.setMemberLevel(memberService.getMemberLevel(member.getConsumeAmt()));
            memberMapper.updateByPrimaryKeySelective(member);
            or.setIsDept(1);
            orderMapper.updateByPrimaryKeySelective(or);
        }
    }

    /**
     * 获取订单以及该订单商品
     */
    public List<Order> findOrderWithGoodsByCondition(Order order) {

        List<Order> result = new ArrayList<Order>();

        //自己买
        order.getOrderCommon().setPostType(1);
        List<Order> orders_self = orderMapper.findOrderWithGoodsByCondition(order);
        Order lastOrder = new Order();  // 相邻的两条记录的上一条
        for (Order record : orders_self) {
            // 待付款时只显示一条，其他状态显示多条
            if ("10".equals(record.getOrderState())) {
                // OrderBatchNumber、BuyerId、AddTime相同的数据，不再进行重复处理
                if (lastOrder.getOrderId() != null) {
                    if (lastOrder.getOrderBatchNumber().equals(record.getOrderBatchNumber()) &&
                            lastOrder.getBuyerId().equals(record.getBuyerId()) && lastOrder.getAddTime() == record.getAddTime() ) {
                        continue;
                    }
                }

                List<Long> batchNumbers_self = orderMapper.findOrderBatchNumber(record);
                for(Long batchNumber:batchNumbers_self){
                    Order param = new Order();
                    param.setOrderBatchNumber(batchNumber);
                    param.setBuyerId(record.getBuyerId());
                    List<Order> orders = orderMapper.findOrderWithGoodsByCondition(param);
                    if(orders.size()>1){
                        Order firstOrder = orders.get(0);
                        List<OrderGoods> orderGoodsList = new ArrayList<OrderGoods>();
                        BigDecimal total = new BigDecimal(0);
                        for(Order order1:orders){
                            orderGoodsList.addAll(order1.getOrderGoodsList());
                            total = total.add(order1.getOrderAmount());
                        }
                        firstOrder.setOrderGoodsList(orderGoodsList);
                        firstOrder.setOrderAmount(total);
                        result.add(firstOrder);
                    }else{
                        result.addAll(orders);
                    }
                }
            } else {
                result.add(record);
            }

            // 保存当前记录，以备下条数据比较用
            lastOrder = record;
        }

        //送朋友
        //获取送朋友的订单的支付号
        order.getOrderCommon().setPostType(2);
        List<Long> batchNumbers = orderMapper.findOrderBatchNumber(order);
        for(Long batchNumber:batchNumbers){

            Order param = new Order();
            param.setOrderBatchNumber(batchNumber);
            List<Order> orders = orderMapper.findOrderWithGoodsByCondition(param);
            if(orders.size()>1){
                Order firstOrder = orders.get(0);
//                    firstOrder.setOrderGoodsList(new ArrayList<OrderGoods>());
                List<OrderGoods> orderGoodsList = new ArrayList<OrderGoods>();
                BigDecimal total = new BigDecimal(0);
                for(Order order1:orders){
                    orderGoodsList.addAll(order1.getOrderGoodsList());
                    total = total.add(order1.getOrderAmount());
                }
                firstOrder.setOrderGoodsList(orderGoodsList);
                firstOrder.setOrderAmount(total);
                result.add(firstOrder);
            }else{
                result.addAll(orders);
            }
        }

        //  对result按照add_time(private int addTime)排序 desc
        Comparator comparator = ComparableComparator.getInstance();
        //逆序（默认为正序）
        comparator = ComparatorUtils. reversedComparator(comparator);

        ArrayList<Object> sortFields = new ArrayList<Object>();
        //主排序（第一排序）
        sortFields.add(new BeanComparator("addTime" , comparator));

        ComparatorChain multiSort = new ComparatorChain(sortFields);
        Collections.sort (result , multiSort);

        return result;
    }

    /**
     * 订单佣金统计报表
     */
    @Transactional
    public void orderCommissionStatistics() {


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format_month = new SimpleDateFormat("yyyyMM");

        //获取前月的第一天
        Calendar cal_1 = Calendar.getInstance();//获取当前日期
        cal_1.add(Calendar.MONTH, -1);
        String last_month = format_month.format(cal_1.getTime());

        cal_1.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String firstDay = format.format(cal_1.getTime());
        System.out.println("-----1------firstDay:" + firstDay);

        //获取前月的最后一天
        Calendar cale = Calendar.getInstance();
        cale.set(Calendar.DAY_OF_MONTH, 0);//设置为1号,当前日期既为本月第一天
        String lastDay = format.format(cale.getTime());
        System.out.println("-----2------lastDay:" + lastDay);


        BigDecimal statisticsOrderAmount_all = new BigDecimal(0);

        BigDecimal statisticsShippingfee_all = new BigDecimal(0);
        BigDecimal statisticsBrokerage_all = new BigDecimal(0);

        Store condition = new Store();
        condition.setStoreState(1);
        condition.setPageSwitch(false);
        List<Store> storeList = storeService.findStoreByCondition(condition);

        for (Store store : storeList) {
            //店铺信息
            Order param = new Order();
            param.setOrderState("30");
            param.setIsDept(0);
            param.setStoreId(store.getStoreId());
            param.setPageSwitch(false);
            List<Order> orders = orderMapper.findLastMonthOrderWithGoodsByCondition(param);
            //统计周期内的佣金
            BigDecimal statisticsBrokerage = new BigDecimal(0);
            //统计周期内的订单总额
            BigDecimal statisticsOrderAmount = new BigDecimal(0);
            //统计周期内的运费
            BigDecimal statisticsShippingfee = new BigDecimal(0);
            for (Order order : orders) {
                BigDecimal brokerage = new BigDecimal(0);
                for (OrderGoods orderGoods : order.getOrderGoodsList()) {
                    Goods goods = goodsMapper.selectByPrimaryKey(orderGoods.getGoodsId());
                    //佣金类型是进销价比例
                    if (goods.getCommissionType() == 1) {
                        brokerage = brokerage.add(goods.getGoodsPrice().subtract(goods.getCostPrice()).multiply(new BigDecimal(goods.getCommissionRate()).divide(new BigDecimal(100))).multiply(new BigDecimal(orderGoods.getGoodsNum())));
                    } else if (goods.getCommissionType() == 2) { //按照售价比例
                        brokerage = brokerage.add(goods.getGoodsPrice().multiply(new BigDecimal(goods.getCommissionRate()).divide(new BigDecimal(100))).multiply(new BigDecimal(orderGoods.getGoodsNum())));

                    } else {
                        //商品佣金类型错误
                        logger.debug("商品佣金类型错误 商品ID" + orderGoods.getGoodsId() + "商品名称" + orderGoods.getGoodsName());

                    }
                }
                order.setIsDept(1);
                order.setOrderState("75");
                orderMapper.updateByPrimaryKeySelective(order);
                OrderLog orderLog = new OrderLog();
                orderLog.setOrderId(order.getOrderId());
                orderLog.setLogTime(DateUtil.unixTimeStampInt().intValue());
                orderLog.setLogUser("0");
                orderLog.setLogRole("0");
                orderLog.setLogOrderstate("30");
                orderLogService.insert(orderLog);

                statisticsOrderAmount = statisticsOrderAmount.add(order.getOrderAmount());
                statisticsShippingfee = statisticsShippingfee.add(order.getShippingFee());
                statisticsBrokerage = statisticsBrokerage.add(brokerage);

            }
            statisticsBrokerage_all = statisticsBrokerage_all.add(statisticsBrokerage);
            statisticsOrderAmount_all = statisticsOrderAmount_all.add(statisticsOrderAmount);
            statisticsShippingfee_all = statisticsShippingfee_all.add(statisticsShippingfee);


            //商户部分
            BigDecimal statisticsResultTotal = statisticsOrderAmount.subtract(statisticsBrokerage);
            OrderBill orderBill = new OrderBill();
            orderBill.setObNo(Integer.parseInt(format_month.format(new Date()) + store.getStoreId()));
            orderBill.setObStoreId(store.getStoreId());
            orderBill.setObStoreName(store.getStoreName());
            orderBill.setObStartDate(DateUtil.toUnixTimeStampByDate(firstDay));
            orderBill.setObEndDate(DateUtil.toUnixTimeStampByDate(lastDay));
            orderBill.setObOrderTotals(statisticsOrderAmount);
            orderBill.setObShippingTotals(statisticsShippingfee);
            orderBill.setObOrderReturnTotals(new BigDecimal(0));
            orderBill.setObCommisTotals(statisticsBrokerage);
            orderBill.setObCommisReturnTotals(new BigDecimal(0));
            orderBill.setObStoreCostTotals(new BigDecimal(0));
            orderBill.setObResultTotals(statisticsResultTotal);
            orderBill.setObCreateDate(DateUtil.unixTimeStampInt().intValue());
            orderBill.setOsMonth(Integer.parseInt(last_month));
            orderBill.setObState("1");
            orderBillMapper.insertSelective(orderBill);
        }


        //平台部分
        BigDecimal statisticsResultTotal_all = statisticsOrderAmount_all.subtract(statisticsBrokerage_all);
        OrderStatis orderStatis = new OrderStatis();
        orderStatis.setOsMonth(Integer.parseInt(last_month));
        orderStatis.setOsYear(Short.parseShort(last_month.substring(0, 4)));
        orderStatis.setOsStartDate(DateUtil.toUnixTimeStampByDate(firstDay));
        orderStatis.setOsEndDate(DateUtil.toUnixTimeStampByDate(lastDay));
        orderStatis.setOsOrderTotals(statisticsOrderAmount_all);
        orderStatis.setOsShippingTotals(statisticsShippingfee_all);
        orderStatis.setOsOrderReturnTotals(new BigDecimal(0));
        orderStatis.setOsCommisTotals(statisticsBrokerage_all);
        orderStatis.setOsCommisReturnTotals(new BigDecimal(0));
        orderStatis.setOsStoreCostTotals(new BigDecimal(0));
        orderStatis.setOsResultTotals(statisticsResultTotal_all);
        orderStatis.setOsCreateDate(DateUtil.unixTimeStampInt().intValue());

        orderStatisMapper.insertSelective(orderStatis);
    }
}
